<template>
  <div class="illustration-gallery">
    <!-- 主要展示区域 -->
    <div class="main-showcase">
      <div class="showcase-container">
        <div class="showcase-content">
          <div class="showcase-text">
            <h1 class="banner-title">收集开源插画资源免费使用</h1>
            <h2 class="showcase-title">小场景大创意</h2>
            <p class="banner-description">分享优秀的系统性插画内容，为平台设计提供更有效的应用资源</p>
          </div>
          <div class="showcase-visual">
            <!-- 这里可以放置主要的插画图片 -->
            <div class="visual-placeholder">
              <div class="floating-icons">
                <div class="icon-item" v-for="(icon, index) in floatingIcons" :key="index" :style="{ left: icon.left, top: icon.top, animationDelay: icon.delay }">
                  <component :is="icon.component" :title="icon.alt" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分类列表 -->
    <div class="category-section">
      <div class="container">
        <!-- 搜索栏 -->
        <div class="search-section">
          <div class="search-container">
            <a-input-search v-model:value="searchKeyword" placeholder="搜索分类名称..." enter-button="搜索" size="large" allow-clear @search="handleSearch" @change="handleSearchChange" :loading="searchLoading" />
            <!-- 搜索结果提示 -->
            <div v-if="searchKeyword" class="search-result-tip">
              <span>搜索 "{{ searchKeyword }}" 的结果（共 {{ categories.length }} 项）</span>
              <a-button type="link" size="small" @click="clearSearch">清除搜索</a-button>
            </div>
          </div>

          <!-- 管理工具栏（仅管理员可见） -->
          <div v-if="isAdmin" class="admin-toolbar">
            <a-button type="primary" @click="handleAddCategory">
              <template #icon>
                <PlusOutlined />
              </template>
              添加分类
            </a-button>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <a-spin size="large" />
        </div>

        <!-- 分类网格 -->
        <div v-else class="category-grid">
          <div class="category-card" v-for="category in categories" :key="category.id" @click="handleCategoryClick(category)">
            <!-- 管理按钮（仅管理员可见） -->
            <div v-if="isAdmin" class="category-actions" @click="stopPropagation">
              <a-button type="text" size="small" @click="handleEditCategory(category)" title="编辑分类">
                <template #icon>
                  <EditOutlined />
                </template>
              </a-button>
              <a-button type="text" size="small" danger @click="handleDeleteCategory(category)" title="删除分类">
                <template #icon>
                  <DeleteOutlined />
                </template>
              </a-button>
            </div>

            <div class="category-image">
              <!-- 有预览图片时显示田字格 -->
              <div v-if="category.thumbnails" class="image-grid">
                <div class="grid-item" v-for="(image, index) in category.thumbnails" :key="index">
                  <img :src="image" :alt="`${category.name} - ${index + 1}`" />
                </div>
              </div>
              <!-- 无预览图片时显示占位内容 -->
              <div v-else class="no-preview">
                <div class="no-preview-icon">
                  <svg width="48" height="48" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z" />
                  </svg>
                </div>
                <p class="no-preview-text">暂无预览</p>
              </div>
            </div>
            <div class="category-info">
              <h3 class="category-name">{{ category.name }}</h3>
              <p class="category-description" v-if="category.description">
                {{ category.description }}
              </p>
              <p class="category-count">插画数量: {{ category.count }}</p>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && categories.length === 0" class="empty-state">
          <a-empty description="暂无分类数据">
            <a-button v-if="isAdmin" type="primary" @click="handleAddCategory"> 创建第一个分类 </a-button>
          </a-empty>
        </div>

        <!-- 加载更多状态 -->
        <div v-if="loadingMore" class="loading-more">
          <a-spin size="large">
            <template #indicator>
              <LoadingOutlined spin />
            </template>
          </a-spin>
          <p>正在加载更多...</p>
        </div>

        <!-- 没有更多数据提示 -->
        <div v-if="!hasMore && categories.length > 0 && !loading" class="no-more-data">
          <a-divider>
            <span class="no-more-text">没有更多数据了 (共 {{ categories.length }} 项)</span>
          </a-divider>
        </div>
      </div>
    </div>

    <!-- 分类管理弹窗 -->
    <IllustrationCategoryModal v-model:open="categoryModalVisible" :category-data="editingCategory" @success="handleCategorySuccess" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { PlusOutlined, EditOutlined, DeleteOutlined, LoadingOutlined, SaveOutlined, TagOutlined, TableOutlined, QuestionCircleOutlined, SafetyOutlined, FileTextOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { getIllustrationCategories, deleteIllustrationCategory } from '@/utils/api'
import IllustrationCategoryModal from '@/components/modals/IllustrationCategoryModal.vue'

const router = useRouter()
const userStore = useUserStore()

// 浮动图标数据
const floatingIcons = ref([
  { component: SaveOutlined, alt: '保存', left: '10%', top: '20%', delay: '0s' },
  { component: TagOutlined, alt: '标签', left: '80%', top: '30%', delay: '1s' },
  { component: EditOutlined, alt: '编辑', left: '15%', top: '60%', delay: '2s' },
  { component: TableOutlined, alt: '表格', left: '70%', top: '70%', delay: '0.5s' },
  { component: QuestionCircleOutlined, alt: '帮助', left: '50%', top: '25%', delay: '1.5s' },
  { component: SafetyOutlined, alt: '安全', left: '25%', top: '80%', delay: '2.5s' }
])

// 分类数据和状态
const categories = ref([])
const loading = ref(false)
const loadingMore = ref(false) // 加载更多状态
const hasMore = ref(true) // 是否还有更多数据
const pagination = ref({
  page: 1,
  limit: 10,
  total: 0,
  totalPages: 0
})

// 搜索相关状态
const searchKeyword = ref('')
const searchLoading = ref(false)

// 弹窗状态
const categoryModalVisible = ref(false)
const editingCategory = ref(null)

// 是否为管理员
const isAdmin = ref(false)

// 检查用户权限
const checkAdminPermission = () => {
  isAdmin.value = userStore.user && userStore.user.username === 'woaichitudouo'
}

/**
 * 获取分类列表
 * @param {boolean} isLoadMore - 是否为加载更多
 * @param {string} search - 搜索关键词
 */
const fetchCategories = async (isLoadMore = false, search = '') => {
  try {
    if (isLoadMore) {
      loadingMore.value = true
    } else {
      loading.value = true
      // 重置数据
      categories.value = []
      pagination.value.page = 1
      hasMore.value = true
    }

    const params = {
      page: pagination.value.page,
      limit: pagination.value.limit
    }

    // 添加搜索参数
    if (search && search.trim()) {
      params.search = search.trim()
    }

    const response = await getIllustrationCategories(params)

    if (response.data) {
      // 处理分类数据，确保每个分类都有预览图片
      const newCategories =
        response.data.categories?.map((category) => ({
          id: category.id,
          name: category.title,
          description: category.description,
          count: category.image_count || 0,
          thumbnails: generateThumbnails(category.preview_illustrations || [])
        })) || []

      if (isLoadMore) {
        // 加载更多时追加数据
        categories.value = [...categories.value, ...newCategories]
      } else {
        // 首次加载时直接设置数据
        categories.value = newCategories
      }

      // 更新分页信息
      if (response.data.pagination) {
        pagination.value = { ...pagination.value, ...response.data.pagination }
        // 检查是否还有更多数据
        hasMore.value = pagination.value.page < pagination.value.totalPages
      } else {
        // 如果没有分页信息，根据返回的数据数量判断
        const hasNewData = newCategories.length > 0
        const isFullPage = newCategories.length === pagination.value.limit
        hasMore.value = hasNewData && isFullPage
      }

      // 数据加载完成后，检查是否需要调整页面高度以支持滚动
      if (!isLoadMore) {
        nextTick(() => {
          const galleryContainer = document.querySelector('.illustration-gallery')
          if (galleryContainer && hasMore.value) {
            const containerHeight = galleryContainer.clientHeight
            const contentHeight = galleryContainer.scrollHeight
            const hasScrollbar = contentHeight > containerHeight

            if (!hasScrollbar) {
              const categorySection = document.querySelector('.category-section')
              if (categorySection) {
                categorySection.style.minHeight = containerHeight + 300 + 'px'
              }
            }
          }
        })
      }
    } else {
      hasMore.value = false
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    message.error(error.message || '获取分类列表失败')
    hasMore.value = false
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

/**
 * 加载更多数据
 */
const loadMore = async () => {
  if (loadingMore.value || !hasMore.value) {
    return
  }

  pagination.value.page += 1
  await fetchCategories(true, searchKeyword.value)
}

/**
 * 生成缩略图数组
 * @param {Array} illustrations - 插画数组
 * @returns {Array} 4张缩略图URL数组，如果没有图片返回null
 */
const generateThumbnails = (illustrations) => {
  // 如果没有插画，返回null表示显示"暂无预览"
  if (!illustrations || illustrations.length === 0) {
    return null
  }

  const baseUrl = import.meta.env.VITE_APP_API_BASE_URL
  const thumbnails = []

  // 使用真实的插画图片
  for (let i = 0; i < Math.min(4, illustrations.length); i++) {
    thumbnails.push(`${baseUrl}${illustrations[i].file_path}`)
  }

  // 如果不足4张，用占位图片补足
  for (let i = thumbnails.length; i < 4; i++) {
    thumbnails.push(`https://picsum.photos/150/100?random=${Date.now()}_${i}`)
  }

  return thumbnails
}

/**
 * 处理分类点击事件
 * @param {Object} category - 分类对象
 */
const handleCategoryClick = (category) => {
  // 构造路由配置
  const routeConfig = {
    name: 'IllustrationDetail',
    params: {
      categoryId: category.id
    },
    query: {
      title: category.name,
      description: category.description
    }
  }

  // 生成完整的URL
  const { href } = router.resolve(routeConfig)

  // 在新窗口中打开详情页面
  window.open(href, '_blank')
}

/**
 * 打开添加分类弹窗
 */
const handleAddCategory = () => {
  editingCategory.value = null
  categoryModalVisible.value = true
}

/**
 * 打开编辑分类弹窗
 * @param {Object} category - 分类对象
 */
const handleEditCategory = (category) => {
  editingCategory.value = {
    id: category.id,
    title: category.name,
    description: category.description
  }
  categoryModalVisible.value = true
}

/**
 * 删除分类
 * @param {Object} category - 分类对象
 */
const handleDeleteCategory = (category) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除分类 "${category.name}" 吗？这将同时删除该分类下的所有插画，此操作不可恢复。`,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await deleteIllustrationCategory(category.id)
        message.success('分类删除成功')
        resetData() // 重置数据
        await fetchCategories() // 刷新列表
      } catch (error) {
        console.error('删除分类失败:', error)
        message.error(error.message || '删除分类失败')
      }
    }
  })
}

/**
 * 分类操作成功回调
 */
const handleCategorySuccess = async () => {
  categoryModalVisible.value = false
  resetData() // 重置数据
  await fetchCategories(false, searchKeyword.value) // 刷新列表，保持搜索状态
}

/**
 * 处理搜索
 * @param {string} value - 搜索关键词
 */
const handleSearch = async (value) => {
  searchKeyword.value = value
  searchLoading.value = true
  try {
    resetData() // 重置分页数据
    await fetchCategories(false, value)
  } finally {
    searchLoading.value = false
  }
}

/**
 * 处理搜索输入变化
 * @param {Event} e - 输入事件
 */
const handleSearchChange = (e) => {
  const value = e.target.value
  // 如果清空了搜索框，立即重新加载数据
  if (!value || value.trim() === '') {
    clearSearch()
  }
}

/**
 * 清除搜索
 */
const clearSearch = async () => {
  searchKeyword.value = ''
  searchLoading.value = true
  try {
    resetData() // 重置分页数据
    await fetchCategories() // 重新加载所有数据
  } finally {
    searchLoading.value = false
  }
}

/**
 * 阻止事件冒泡
 */
const stopPropagation = (event) => {
  event.stopPropagation()
}

/**
 * 滚动事件处理
 */
const handleScroll = (event) => {
  // 如果正在加载或没有更多数据，直接返回
  if (loadingMore.value || !hasMore.value) {
    return
  }

  const target = event.target
  const scrollTop = target.scrollTop
  const scrollHeight = target.scrollHeight
  const clientHeight = target.clientHeight
  const distanceToBottom = scrollHeight - (scrollTop + clientHeight)

  // 当滚动到距离底部150px时触发加载更多
  if (distanceToBottom <= 150) {
    loadMore()
  }
}

/**
 * 节流函数
 */
const throttle = (func, delay) => {
  let timeout = null
  return function (...args) {
    if (!timeout) {
      func.apply(this, args)
      timeout = setTimeout(() => {
        timeout = null
      }, delay)
    }
  }
}

/**
 * 重置分页和数据
 */
const resetData = () => {
  categories.value = []
  pagination.value.page = 1
  hasMore.value = true
  loadingMore.value = false
}

// 创建节流后的滚动处理函数
const throttledHandleScroll = throttle(handleScroll, 100)

// 监听用户状态变化，动态更新管理员权限
watch(
  () => userStore.user,
  () => {
    checkAdminPermission()
  },
  { immediate: true }
)

// 页面加载时获取数据和设置滚动监听
onMounted(async () => {
  await fetchCategories()

  // 添加滚动监听到正确的容器
  nextTick(() => {
    const galleryContainer = document.querySelector('.illustration-gallery')
    if (galleryContainer) {
      galleryContainer.addEventListener('scroll', throttledHandleScroll, { passive: true })
    }
  })
})

// 页面卸载时移除滚动监听
onUnmounted(() => {
  const galleryContainer = document.querySelector('.illustration-gallery')
  if (galleryContainer) {
    galleryContainer.removeEventListener('scroll', throttledHandleScroll)
  }
})
</script>
<style scoped>
@import './index.css';
</style>
